using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Magiq.Delete;

namespace Magiq.Insert {
  public class EnumerableInsert<F, T> : IEnumerableInsert<T> {
    private readonly EnumerableSourceFinder enumerableSourceFinder = new EnumerableSourceFinder();
    private readonly Expression<Func<F, T>> newExpression;

    private readonly IEnumerable<F> where;

    public EnumerableInsert(IEnumerable<F> where, Expression<Func<F, T>> newValueExpression) {
      this.where = where;
      newExpression = newValueExpression;
    }

    #region IEnumerableInsert<T> Members

    public int Into(IEnumerable<T> destination) {
      return Into((IEnumerable) destination);
    }

    public int Into(IEnumerable destination) {
      var collection = enumerableSourceFinder.FindSourceOf(destination);
      var count = 0;
      var @new = newExpression.Compile();
      foreach (var item in where.ToArray()) {
        collection.Add(@new(item));
        count++;
      }
      return count;
    }

    #endregion
  }
}